import { connect } from 'dva';
import PropTypes from 'prop-types';
import { Card, Table, Popconfirm, Button } from 'antd';
import { routerRedux } from 'dva/router';
import styles from './Privileges.css';
import { PAGE_SIZE } from '../constants';
import PrivilegeModal from './PrivilegeModal';
import CustomPagin from 'components/CustomPagin';

function privileges({ dispatch, items: dataSource, loading, total, page: current }) {
  function deleteHandler(id) {
    dispatch({
      type: 'privileges/remove',
      payload: id,
    });
  }

  function pageChangeHandler(page) {
    dispatch(
      routerRedux.push({
        pathname: '/privileges',
        query: { page },
      })
    );
  }

  function editHandler(id, values) {
    dispatch({
      type: 'privileges/patch',
      payload: { id, values },
    });
  }

  function createHandler(values) {
    dispatch({
      type: 'privileges/create',
      payload: values,
    });
  }

  const columns = [
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      render: text => <a href="">{text}</a>,
    },
    {
      title: 'Email',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: 'Website',
      dataIndex: 'website',
      key: 'website',
    },
    {
      title: 'Operation',
      key: 'operation',
      render: (text, record) => (
        <span className={styles.operation}>
          <PrivilegeModal record={record} onOk={editHandler.bind(null, record.id)}>
            <a>Edit</a>
          </PrivilegeModal>
          <Popconfirm title="Confirm to delete?" onConfirm={deleteHandler.bind(null, record.id)}>
            <a href="">Delete</a>
          </Popconfirm>
        </span>
      ),
    },
  ];

  return (
    <div className={styles.normal}>
      <Card className={styles.create}>
        <PrivilegeModal record={{}} onOk={createHandler}>
          <Button type="primary">添加权限</Button>
        </PrivilegeModal>
      </Card>
      <Card>
        <Table
          bordered
          loading={loading}
          columns={columns}
          dataSource={dataSource}
          rowKey={record => record.id}
          pagination={false}
        />
        <CustomPagin
          total={total}
          current={current}
          pageSize={PAGE_SIZE}
          onChange={pageChangeHandler}
        />
      </Card>
    </div>
  );
}

if (process.env.UMI_ENV !== 'prod') {
  privileges.propTypes = {
    dispatch: PropTypes.func.isRequired,
    total: PropTypes.number.isRequired,
    items: PropTypes.array.isRequired,
    page: PropTypes.number.isRequired,
    loading: PropTypes.bool.isRequired,
  };
}

privileges.defaultProps = {
  dispatch: () => {},
  total: 0,
  items: [],
  page: 1,
  loading: false,
};

function mapStateToProps(state) {
  const { items, total, page } = state.privileges;
  return {
    items,
    total,
    page,
    loading: state.loading.models.privileges,
  };
}

export default connect(mapStateToProps)(privileges);
